package com.authine.cloudpivot.ext.controller.FinancingScale;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/public/suppcredit")
@Slf4j
public class suppcredit extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  信用额度  审批流完成后 数据写到-信用额度 基础
     */
    @RequestMapping("finish")
    public void finish(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.suppcredit, bizId);
        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetCreditLineNew");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //获取审批人
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        for (Map<String, Object> map : list) {
            String companyNumber = (String) map.get("txtComCode");
            String CASNumber = (String) map.get("SuppCode");
            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CreditLineBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-信用额度操作成功 ");
                //调用存储过程
                callProcess(id);
            } catch (Exception e) {
                log.info("基础表-信用额度操作失败 companyNumber={},CASNumber={}", companyNumber,CASNumber);
                log.info(e.getMessage(), e);
            }
        }
    }
    @RequestMapping("toVoid")
    public void toVoid(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.creditlinevoid, bizId);
        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetCreditLineVoid");

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
//            String oneLevelCode = (String) map.get("oneLevelCode");
//            String funCode = (String) map.get("funCode");

            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(data);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }

                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CreditLineBase, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-信用额度作废操作成功 ");
                //调用存储过程
                callProcessToVoid(id);

            } catch (Exception e) {
//                log.info("基础表-总公司档案作废操作失败 oneLevelCode={},funCode={}", oneLevelCode,funCode);
//                log.info(e.getMessage(), e);
            }

        }
    }

    @RequestMapping("jieyu")
    public void jieyu(String bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.creditbalancebill, bizId);
        List<Map<String,Object>> list = (List<Map<String, Object>>) bizObject.get("SheetCreditBalanceBill");
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //获取审批人
        String approval = "";
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject);
        for (Map<String, Object> map : list) {
            String companyNumber = (String) map.get("txtComCode");
            String CASNumber = (String) map.get("SuppCode");
            try {
                //获取数据
                Map<String, Object> data = fileInfoBaseMap01(map, now, approval);
                //判断是否已存在
                String id = existsBizObject(map);
                if (StringUtils.isNotEmpty(id)) {
                    data.put("id", id);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.CreditLineBase, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                id = getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                log.info("基础表-信用额度结余操作成功 ");
                //调用存储过程
                callProcess01(id);
            } catch (Exception e) {
                log.info("基础表-信用额度操作失败 companyNumber={},CASNumber={}", companyNumber,CASNumber);
                log.info(e.getMessage(), e);
            }
        }
    }

    /**
     *  调用存储过程
     create  proc   SyncCreditLine       -----往来单位信用  新增
     (
     @ComCode   nvarchar(10),    ----公司代码
     @SuppCode  nvarchar(50),	----往来单位代码
     @SimpleName  nvarchar(50),	----简称
     @BegDate   nvarchar(50),	----开启日
     @Enddate   nvarchar(50),	----到期日
     @flevel     nvarchar(10),	----等级
     @creditline     decimal(10,4),		----额度
     @condition  nvarchar(255),		----结算条件
     @longDesc   nvarchar(255),		----说明
     @auditdate  nvarchar(50)		----审批时间
     )


      * @param bizId
     */
    private void callProcess(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        BigDecimal zero= BigDecimal.valueOf(0);
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CreditLineBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程
        String ComCode = MapUtils.getString(map,"ComCode","");
        String SuppCode = MapUtils.getString(map,"SuppCode","");//往来单位代码
        String Simple  = MapUtils.getString(map,"Simple","");//简称

        LocalDateTime BegDateTemp = (LocalDateTime) map.get("BegDate");
        String BegDate =  ObjectUtils.isEmpty(BegDateTemp) ? "" : BegDateTemp.toLocalDate().toString();
        LocalDateTime EndDateTemp = (LocalDateTime) map.get("EndDate");
        String EndDate =  ObjectUtils.isEmpty(EndDateTemp) ? "" : EndDateTemp.toLocalDate().toString();

        String CreditLvl  = MapUtils.getString(map,"Level","");//等级

        double NumCreditLine = ((BigDecimal)map.get("CreditLine")).doubleValue();//额度
        String Condition  = MapUtils.getString(map,"Condition","");//

        String LongDesc = MapUtils.getString(map,"LongDesc","");
        String auditDate = MapUtils.getString(map,"auditDate","");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCreditLine '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                ComCode,SuppCode,Simple,BegDate,EndDate,CreditLvl,NumCreditLine,Condition,LongDesc,auditDate );

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  调用作废存储过程
     create  proc   CreditLineVoid       -----往来单位信用  作废
     (
     @ComCode   nvarchar(10),    ----公司代码
     @SuppCode  nvarchar(50),	----往来单位代码
     @auditdate  nvarchar(50)		----审批时间
     )

      * @param bizId
     */
    private void callProcessToVoid(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CreditLineBase);
        StringBuilder sql = new StringBuilder("SELECT * from  ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程

        String ComCode = MapUtils.getString(map,"ComCode","");
        String SuppCode = MapUtils.getString(map,"SuppCode","");//往来单位代码
        String auditDate = MapUtils.getString(map,"auditDate","");
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].CreditLineVoid '%s','%s','%s'",
                ComCode,SuppCode,auditDate );

        log.info("\n==========准备调用作废存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============作废存储过程执行完成");

    }
    /**
     *  调用存储过程
     create  proc   CreditLineUse      -----往来单位信用  结余
     (
     @ComCode   nvarchar(10),    ----公司代码
     @SuppCode  nvarchar(50),	----往来单位代码
     @used	decimal(10,4),		----使用
     @balance  decimal(10,4),		----余额
     @longDesc   nvarchar(255),		----说明
     @auditdate  nvarchar(50)		----审批时间
     )

      * @param bizId
     */
    private void callProcess01(String bizId){

        if (StringUtils.isEmpty(bizId)) {
            return;
        }
        BigDecimal zero= BigDecimal.valueOf(0);
        //编写sql
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CreditLineBase);
        StringBuilder sql = new StringBuilder("SELECT * from ")
                .append(tableName).append(" where id ='")
                .append(bizId).append("';");
        //查询到入参
        Map<String, Object> map = sqlService.getMap(sql.toString());

        log.info("入参map={}",map);

        //调用存储过程
        String ComCode = MapUtils.getString(map,"ComCode","");
        String SuppCode = MapUtils.getString(map,"SuppCode","");//往来单位代码
        double Used = ((BigDecimal)map.get("Used")).doubleValue();//使用
        double Balance = ((BigDecimal)map.get("Balance")).doubleValue();//结余

        String LongDesc = MapUtils.getString(map,"LongDesc","");
        String auditDate = MapUtils.getString(map,"auditDate","");

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].CreditLineUse '%s','%s','%s','%s','%s','%s'",
                ComCode,SuppCode,Used,Balance,LongDesc,auditDate );

        log.info("\n==========准备调用存储过程:{}",execSql);

        sqlService.execute(CloudSqlService.htEas,execSql);

        log.info("\n=============存储过程执行完成");

    }
    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity14";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(" ").append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @return
     */
    private String existsBizObject(Map data){

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.CreditLineBase);
//        String companyNumber = (String) data.get("companyNumber");//公司
        String SuppCode = (String) data.get("SuppCode");//往来单位代码
//        String ItemNumber = (String) data.get("txtItemCode");//事项号
//        Date openingDateTemp = (Date) data.get("openingDate");
//        String openingDate = DateFormatUtils.format(openingDateTemp, "yyyy-MM-dd");


        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where SuppCode='").append(SuppCode).append("';");
//                .append("' and CASNumber='")
//                .append(CASNumber).append("' and txtItemCode='")
//                .append(ItemNumber)

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-融资 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();

        //公司
        data.put("ComCode",map.get("txtComCode"));
        //往来单位代码
        data.put("SuppCode",map.get("SuppCode"));
        //简称
        data.put("Simple",map.get("txtsimple"));
        //主责部门
        data.put("MainDept",map.get("txtMainDept"));
        //岗A
        data.put("PosA",map.get("txtPosA"));



        //开启日
        data.put("BegDate",map.get("BegDate"));
        //到期日
        data.put("EndDate",map.get("EndDate"));
        //资信风险
        data.put("CreditRisk",map.get("NumCreditRisk"));
        //结算条件
        data.put("Condition",map.get("Condition"));

        //综合评分
        data.put("Total",map.get("NumTotal"));
        //信用等级
        data.put("Level",map.get("CreditLvl"));
        //合同账期
        data.put("ContractTerm",map.get("NumContractTerm"));
        //信用账期
        data.put("CreditTerm",map.get("NumCreditTerm"));

        //信用额度
        data.put("CreditLine",map.get("NumCreditLine"));
//        //使用
//        data.put("Used",map.get("posBNumber"));
//        //结余
//        data.put("Balance",map.get("posBName"));
        //说明
        data.put("LongDesc",map.get("LongDesc"));


        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }
    /**
     *  转换成  基础表-融资 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap01(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();

        data.put("Used",map.get("NumUsed"));
        data.put("Balance",map.get("NumBalance"));

        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);

        return data;
    }
}
